var findMaxLength = function (nums) {
  if(nums.length == 0) {
    return 0
  }
  let count = 0;
  let map = new Map()
  let maxLength = 0
  for(let i = 0; i<nums.length; i++) {
    if(nums[i] == 1) {
      count++
    }else {
      count--
    }

    if(map.has(count)) {
      let position = map.get(count)
      maxLength = Math.max(maxLength, i-position)
    }else {
      map.set(count, i)
    }
  }
  return maxLength
};


var findMaxLength1 = function (nums) {
  let maxLength = 0;
  const map = new Map();
  let counter = 0;
  map.set(counter, -1);
  const n = nums.length;
  for (let i = 0; i < n; i++) {
    const num = nums[i];
    if (num == 1) {
      counter++;
    } else {
      counter--;
    }
    if (map.has(counter)) {
      const prevIndex = map.get(counter);
      console.log(maxLength);
      maxLength = Math.max(maxLength, i - prevIndex);
    } else {
      map.set(counter, i);
    }
  }
  console.log(map);
  return maxLength;
};

console.log(findMaxLength([0, 0, 1, 0, 0, 0, 1, 1]));